package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@WebFilter(value = "authorFilter",urlPatterns = "/*")
@Slf4j
public class AuthorFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1 获取请求头中的用户id(doFilter请求前处理)
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String userId = request.getHeader("userId");
        //如果存在 将用户id设置到线程变量中
        if (StringUtils.isNotBlank(userId)){
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtils.setUser(wmUser);

            log.info("当前登录用户为:{}",userId);//打印日志
        }

        //3 放行请求
        filterChain.doFilter(servletRequest,servletResponse);//(doFilter响应前处理)

        //4 清空threadlocal
        WmThreadLocalUtils.clear();



    }
}
